package com.lagou.handle;

import com.alibaba.fastjson.JSON;
import com.lagou.util.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;
import java.util.Map;

public class HelloServiceHandle extends ChannelInboundHandlerAdapter {
    private Map<String,Object> ioc;

    public HelloServiceHandle(Map<String,Object> ioc){
        this.ioc = ioc;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //判断是否符合调用规则   HelloService#sayHello#msg
//        if (msg.toString().startsWith("HelloService")){
//            //创建服务实现类调用服务
//            HelloServiceImpl helloService = new HelloServiceImpl();
//            String result = helloService.sayHello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
//            //返回结果
//            ctx.writeAndFlush(result);
//        }

        if (msg != null && msg instanceof RpcRequest){
            System.out.println("请求参数为："+ JSON.toJSONString(msg));
            RpcRequest request = (RpcRequest) msg;
            String className = request.getClassName();
            Object o = ioc.get(className);
            String methodName = request.getMethodName();
            Method method = o.getClass().getMethod(methodName, request.getParameterTypes());
            Object result = method.invoke(o, request.getParameters());
            System.out.println("服务端处理结果为："+ JSON.toJSONString(result));
            ctx.writeAndFlush(result);
        }
    }
}
